'use strict';

let baseSecret = 'shanghaiguojiyalanmeiyitong2017'

module.exports = class extends think.Controller {
	
	// 简单的加密解密算法

	// 加密
	cipher (json, key) {
		json = this.cipherbase64(json)
		const crypto = require('crypto')
		const cipher = crypto.createCipher('aes192', key)
		let res = cipher.update(json, 'utf8', 'base64')
		res += cipher.final('base64')
		return res
	}

	// 解密
	decipher (secret, key) {
		const crypto = require('crypto')
		try {
			const decipher = crypto.createDecipher('aes192', key)
			let res = decipher.update(secret, 'base64', 'utf8')
			res += decipher.final('utf8')
			res = new Buffer(res, 'base64').toString()
			return JSON.parse(res)
		} catch (e) {
			console.log(e)
			return false
		}
	}


	// 摘要算法
	createHmac (str) {
		const crypto = require('crypto')
		const hmac = crypto.createHmac('sha256', baseSecret)
		hmac.update(str)
		return hmac.digest('hex')
	}

	// 转换成base64
	cipherbase64 (json) {
		return new Buffer(JSON.stringify(json)).toString('base64')
	}

	decipherbase64 (str) {
		return JSON.parse(new Buffer(str, 'base64').toString())
	}
}